from django.db import connection


class DBUtils:
    def dictfetchall(self, cursor):
        "Return all rows from a cursor as a dict"
        desc = cursor.description
        if desc == None:
            return []
        columns = [col[0] for col in desc]
        # for row in cursor.fetchall():
        #     rows.append(row)
        return [
            dict(zip(columns, row))
            for row in cursor.fetchall()
        ]

    def dictfetone(self, cursor):
        desc = cursor.description
        if desc == None:
            return None
        columns = [col[0] for col in desc]
        row = cursor.fetchone()
        if row == None:
            return None
        return dict(zip(columns, row))

    def fetchall(self, sql, params=[]):
        cursor = connection.cursor()
        cursor.execute(sql, params)
        ret = self.dictfetchall(cursor)
        return ret

    def fetchone(self, sql, params=[]):
        cursor = connection.cursor()
        cursor.execute(sql, params)
        ret = self.dictfetone(cursor)
        cursor.close()
        return ret

    def executeDb(sql, params=[]):
        cursor = connection.cursor()
        ret = cursor.execute(sql, params)
        cursor.close()
        return ret
